package com.moodbox.server.common.controller;

import com.moodbox.server.common.annotation.RequireRole;
import com.moodbox.server.common.enums.UserRoleEnum;
import com.moodbox.server.common.service.SensitiveWordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/sensitive-words")
@RequiredArgsConstructor
public class SensitiveWordController {

    private final SensitiveWordService sensitiveWordService;

    /**
     * 添加单个敏感词
     * @param word 敏感词
     * @return 响应结果
     */
    @PostMapping("/add")
    @RequireRole(value = UserRoleEnum.ADMIN, strict = true)
    public ResponseEntity<String> addSensitiveWord(
        @RequestParam String word,
        @RequestHeader("Authorization") String userId
    ) {
        sensitiveWordService.addSensitiveWord(word);
        log.info("用户{}添加敏感词：{}", userId, word);
        return ResponseEntity.ok("敏感词添加成功");
    }

    /**
     * 批量添加敏感词
     * @param file 敏感词文件
     * @return 响应结果
     */
    @PostMapping("/upload")
    @RequireRole(value = UserRoleEnum.ADMIN, strict = true)
    public ResponseEntity<String> uploadSensitiveWords(
        @RequestParam("file") MultipartFile file,
        @RequestHeader("Authorization") String userId
    ) {
        try {
            // 读取文件内容
            List<String> words = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8)
            ).lines()
             .filter(line -> !line.trim().isEmpty() && !line.trim().startsWith("#"))
             .map(String::trim)
             .collect(Collectors.toList());

            // 批量添加敏感词
            words.forEach(sensitiveWordService::addSensitiveWord);

            log.info("用户{}上传并添加{}个敏感词", userId, words.size());
            return ResponseEntity.ok("成功添加 " + words.size() + " 个敏感词");
        } catch (Exception e) {
            log.error("敏感词上传失败", e);
            return ResponseEntity.badRequest().body("敏感词上传失败：" + e.getMessage());
        }
    }

    /**
     * 移除单个敏感词
     * @param word 敏感词
     * @return 响应结果
     */
    @DeleteMapping("/remove")
    @RequireRole(value = UserRoleEnum.ADMIN, strict = true)
    public ResponseEntity<String> removeSensitiveWord(
        @RequestParam String word,
        @RequestHeader("Authorization") String userId
    ) {
        sensitiveWordService.removeSensitiveWord(word);
        log.info("用户{}移除敏感词：{}", userId, word);
        return ResponseEntity.ok("敏感词移除成功");
    }

    /**
     * 检查文本是否包含敏感词
     * @param text 待检查的文本
     * @return 是否包含敏感词
     */
    @PostMapping("/check")
    public ResponseEntity<SensitiveWordCheckResult> checkSensitiveWord(
        @RequestParam String text
    ) {
        boolean containsSensitiveWord = sensitiveWordService.containsSensitiveWord(text);
        String filteredText = sensitiveWordService.filterSensitiveWord(text);

        SensitiveWordCheckResult result = new SensitiveWordCheckResult(
            containsSensitiveWord, 
            filteredText
        );

        return ResponseEntity.ok(result);
    }

    /**
     * 获取敏感词列表
     * @return 敏感词列表
     */
    @GetMapping("/list")
    @RequireRole(value = UserRoleEnum.ADMIN)
    public ResponseEntity<List<String>> listSensitiveWords() {
        List<String> sensitiveWords = sensitiveWordService.getSensitiveWords();
        return ResponseEntity.ok(sensitiveWords);
    }

    /**
     * 敏感词检查结果
     */
    public static class SensitiveWordCheckResult {
        public boolean containsSensitiveWord;
        public String filteredText;

        public SensitiveWordCheckResult(boolean containsSensitiveWord, String filteredText) {
            this.containsSensitiveWord = containsSensitiveWord;
            this.filteredText = filteredText;
        }
    }
} 